import axios from "axios";
import { getToken, removeToken } from './token'
import router from '@/router'
import { message } from "antd";

const request = axios.create({
    baseURL: process.env.REACT_APP_BASE_URL || 'https://geek.itheima.net/v1_0',
    timeout: 10000
})

//请求拦截器
request.interceptors.request.use((config) => {
    const token = getToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

//返回拦截器
request.interceptors.response.use((response) => {
    return response.data
}, (error) => {
    return Promise.reject(handleError(error))
})

//返回错误处理函数
const handleError = (error) => {
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
        return {
            //此处可以按照与后端的预定，限制 此处的内容格式
            code: 408,
            message: '请求超时,请重试'
        }
    } else if (error.response && error.response.status === 401) {
        return {
            code: 401,
            message: '认证过期,请重新登录'
        }
    }
    return {
        code: 500,
        message: error.message || '请求失败,请稍后重试'
    }
}

async function createApiRequest(method, url, data) {
    try {
        return await request({
            method,
            url,
            ...(method === 'GET' ? { params: data } : { data })
        })
    } catch (error) {
        if (error.code === 401) {
            removeToken()
            router.navigate('/login')
            message.error(error.message)
            return Promise.resolve()
        } else if (error.code === 408) {
            message.error(error.message)
            return Promise.resolve()
        }
        return Promise.reject(error)
    }
}

export { createApiRequest }